package com.coocaa.cirrus.admin.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author bijiahao
 * @date : 2025/7/9 17:02
 * @description
 */
@Configuration
@MapperScan(basePackages = {"com.coocaa.typhoon.admin.v1.**.mapper","com.coocaa.cirrus.common.biz.**.mapper"},
        sqlSessionTemplateRef = "tenantSqlSessionTemplate",
        sqlSessionFactoryRef = "tenantSqlSessionFactory")
public class MyBatisConfig {

    /**
     * 创建数据源
     */
    @Bean
    @ConfigurationProperties(prefix = "tenant.datasource")
    @Primary
    public DataSource tenantDataSource() {
        return new DruidDataSource();
    }

    @Bean
    @Primary
    public SqlSessionFactory tenantSqlSessionFactory(@Qualifier("tenantDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:com/coocaa/cirrus/admin/v1/**/mapper/*.xml,"
                        + "classpath*:com.coocaa.cirrus.common.biz/*/mapper/*.xml"
                ));
        return factoryBean.getObject();
    }

    /**
     * 创建事务
     */
    @Bean
    @Primary
    public DataSourceTransactionManager tenantTransactionManager(@Qualifier("tenantDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 创建模板
     */
    @Bean
    @Primary
    public SqlSessionTemplate tenantSqlSessionTemplate(@Qualifier("tenantSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
